package org.jeecg.common.util.xinyuan;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.*;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 
 *AES工具类
 *
 * @修改记录（修改时间、作者、原因）：
 */
public class AES {
    private static final String ALGORITHM = "AES";
    private Cipher encCipher;
    private Cipher decCipger;
    private SecretKeySpec keySpec;
    private IvParameterSpec ivSpec;

    /**
     * 初始化
     *
     * @param key    密钥
     * @param keyoff key中的偏移量，密钥内容从此处开始
     * @param keylen 密钥长度
     * @param iv     初始化向量 (IV)
     * @param ivoff  iv中的偏移量，初始化向量内容从此处开始
     */
    public void init(byte key[], int keyoff, int keylen, byte iv[], int ivoff) {
        this.keySpec = new SecretKeySpec(key, keyoff, keylen, ALGORITHM);
        this.ivSpec = new IvParameterSpec(iv, ivoff, 16);
    }

    /**
     * 初始化
     *
     * @param key 密钥
     * @param iv  初始化向量 (IV)
     */
    public void init(byte key[], byte iv[]) {
        this.keySpec = new SecretKeySpec(key, ALGORITHM);
        this.ivSpec = new IvParameterSpec(iv);
    }

    public void init(byte key[]) {
        this.keySpec = new SecretKeySpec(key, ALGORITHM);
        this.ivSpec = null;
    }

    /**
     * 加密
     *
     * @param indata  输入缓冲区
     * @param inoff   input中输入起始处的偏移量
     * @param inlen   输入长度
     * @param outdata 输出缓冲区
     * @param outoff  output中存储结果处的偏移量
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws ShortBufferException               输出缓冲区太小
     * @throws IllegalBlockSizeException          块密码的数据长度不正确
     * @throws BadPaddingException                数据期望特定的填充机制而数据又未正确填充
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     */
    public void encrypt(byte indata[], int inoff, int inlen, byte outdata[], int outoff) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        this.initEncryptor();
        this.encCipher.doFinal(indata, inoff, inlen, outdata, outoff);
    }

    /**
     * 加密
     *
     * @param indata 输入缓冲区
     * @param inoff  input中输入起始处的偏移量
     * @param inlen  输入长度
     * @return 加密后的字节数组
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws ShortBufferException               输出缓冲区太小
     * @throws IllegalBlockSizeException          块密码的数据长度不正确
     * @throws BadPaddingException                数据期望特定的填充机制而数据又未正确填充
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     */
    public byte[] encrypt(byte indata[], int inoff, int inlen) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        this.initEncryptor();
        return this.encCipher.doFinal(indata, inoff, inlen);
    }

    /**
     * 加密
     *
     * @param indata 输入缓冲区
     * @return 加密后的字节数组
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     * @throws IllegalBlockSizeException          块密码的数据长度不正确
     * @throws BadPaddingException                数据期望特定的填充机制而数据又未正确填充
     */
    public byte[] encrypt(byte indata[]) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        this.initEncryptor();
        return this.encCipher.doFinal(indata);
    }

    /**
     * 解密
     *
     * @param indata  输入缓冲区
     * @param inoff   input中输入起始处的偏移量
     * @param inlen   输入长度
     * @param outdata 输出缓冲区
     * @param outoff  output中存储结果处的偏移量
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws ShortBufferException               输出缓冲区太小
     * @throws IllegalBlockSizeException          块密码的数据长度不正确
     * @throws BadPaddingException                数据期望特定的填充机制而数据又未正确填充
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     */
    public void decrypt(byte indata[], int inoff, int inlen, byte outdata[], int outoff) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
        this.initDecryptor();
        this.decCipger.doFinal(indata, inoff, inlen, outdata, outoff);
    }

    /**
     * 解密
     *
     * @param indata 输入缓冲区
     * @param inoff  input中输入起始处的偏移量
     * @param inlen  输入长度
     * @return 解密后的字节数组
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws IllegalBlockSizeException          块密码的数据长度不正确
     * @throws BadPaddingException                数据期望特定的填充机制而数据又未正确填充
     * @throws ShortBufferException               输出缓冲区太小
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     */
    public byte[] decrypt(byte indata[], int inoff, int inlen) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, ShortBufferException, InvalidAlgorithmParameterException {
        this.initDecryptor();
        return this.decCipger.doFinal(indata, inoff, inlen);
    }

    /**
     * 解密
     *
     * @param indata 输入缓冲区
     * @return 解密后的字节数组
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     * @throws IllegalBlockSizeException          块密码的数据长度不正确
     * @throws BadPaddingException                数据期望特定的填充机制而数据又未正确填充
     */
    public byte[] decrypt(byte indata[]) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        this.initDecryptor();
        return this.decCipger.doFinal(indata);
    }

    /**
     * 初始化加密chpher
     *
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws InvalidKeyException                无效Key
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     */
    private void initEncryptor() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
        if (this.encCipher == null) {
            if (this.ivSpec == null) {
                this.encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                this.encCipher.init(1, this.keySpec);
            } else {
                this.encCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                this.encCipher.init(1, this.keySpec, this.ivSpec);
            }
        }
    }

    /**
     * 初始化解密chipher
     *
     * @throws NoSuchPaddingException             填充机制不存在
     * @throws NoSuchAlgorithmException           算法不存在
     * @throws InvalidKeyException                无效Key
     * @throws InvalidAlgorithmParameterException 无效或不合适的算法参数
     */
    private void initDecryptor() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
        if (this.decCipger == null) {
            if (this.ivSpec == null) {
                this.decCipger = Cipher.getInstance("AES/ECB/PKCS5Padding");
                this.decCipger.init(2, this.keySpec);
            } else {
                this.decCipger = Cipher.getInstance("AES/CBC/PKCS5Padding");
                this.decCipger.init(2, this.keySpec, this.ivSpec);
            }
        }
    }


    // 加密
    public static String encry(Object content,String key) {
        String json = JSON.toJSONString(content);
        // IV为商户MD5密钥后16位
        String IV = key.substring(key.length() - 16);
        // RES的KEY 为商户MD5密钥的前16位
        String keys = key.substring(0, 16);
        return encryptData(json, keys, IV);
    }

    // 解密
    public static String desEncry(String content,String key) {
        // IV为商户MD5密钥后16位
        String IV = key.substring(key.length() - 16);
        // RES的KEY 为商户MD5密钥的前16位
        String keys = key.substring(0, 16);
        return decryptData(content, keys, IV);
    }

    /**
     * aes 加密
     * @param data 明文
     */
    private static String encryptData(String data, String key, String IV){
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
            int plaintextLength = dataBytes.length;
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new String(Base64.encodeBase64(encrypted));
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 解密
     * @param data 密文
     */
    private static String decryptData(String data, String key, String IV) {
        try {
            byte[]encrypted1 = Base64.decodeBase64(data.getBytes(StandardCharsets.UTF_8));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    //测试=====================
    //使用测试01


    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param key 加密密钥
     * @param iv 向量
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String key, String iv) {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec ivParameter = new IvParameterSpec(iv.getBytes("utf-8"));

            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key),  ivParameter);

            // 加密
            byte[] result = cipher.doFinal(content.getBytes("utf-8"));

            //通过Base64转码返回
            return com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(result);

        } catch (Exception ex) {
//            throw new Exception("AES加密失败！"+ex.getMessage(),ex);
        }
        return "";
    }

    public static void main(String[] args) throws IOException {
        File file = new File("D:/test/project.json" );
        String jsonContent = FileUtils.readFileToString(file,"UTF-8");
        String result = encrypt(jsonContent,"1234567812345678","1000000000000000");

        File projectInfoFile = new File("D:/test/project2.json");
        try (FileWriter fileWriter = new FileWriter(projectInfoFile);
             BufferedWriter out = new BufferedWriter(fileWriter)
        ) {
            out.write(result);
        } catch (Exception e) {
            e.printStackTrace();
        }


        File file2 = new File("D:/test/project2.json" );
        String fileContent = FileUtils.readFileToString(file2,"UTF-8");
        String result2 = decrypt(fileContent,"1234567812345678","1000000000000000");

        File projectInfoFile2 = new File("D:/test/project3.json");
        try (FileWriter fileWriter = new FileWriter(projectInfoFile2);
             BufferedWriter out = new BufferedWriter(fileWriter)
        ) {
            out.write(result2);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * AES 解密操作
     *
     * @param content 密文
     * @param key 加密密钥
     * @param iv 向量
     * @return 返回解密后的明文
     */
    public static String decrypt(String content, String key, String iv) {

        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            IvParameterSpec ivParameter = new IvParameterSpec(iv.getBytes("utf-8"));

            // 使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key), ivParameter);

            // 解密
            byte[] result = cipher.doFinal(com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(content));

            // 返回解密后的明文
            return new String(result, "utf-8");
        } catch (Exception ex) {
//            throw new Exception("AES解密失败！"+ex.getMessage(),ex);
        }
        return "";
    }

    /**
     * 生成加密秘钥
     *
     * @return
     * @throws Exception 
     */
    private static SecretKeySpec getSecretKey(String key) throws Exception {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;

        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);

            //兼容linux和window的内核
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes(Charset.forName("UTF-8")));

            //AES 要求密钥长度为 128
            kg.init(128, secureRandom);

            //生成一个密钥
            SecretKey secretKey = kg.generateKey();

            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            throw new Exception("AES生成加密秘钥失败！"+ex.getMessage(),ex);
        }
    }
}